<template>
  <div class="order-wrapper">
    <div class="desc fs16 mb-3" v-html="currentGoods.description"></div>
    <div class="d-flex flex-wrap space-between">
      <div class="grid">
        <div class="header">
          <el-select v-model="name" placeholder="" @change="handleChange">
            <el-option :label="item.name" :value="item.id" v-for="item in goods" :key="item.id"></el-option>
          </el-select>
        </div>
        <div class="inner">
          <div class="info fs14">
            <div class="account">账号：{{ this.$store.state.username }}</div>
            <!-- <div class="level d-flex space-between">
              <span>等级：{{ account.level }}</span>
              <span style="display: none">
                <el-button type="warning" size="mini">升级</el-button>
              </span>
            </div> -->
            <div class="balance d-flex space-between">
              <span>余额：{{ account.balance }} 元</span>
              <span>
                <el-button type="primary" size="mini" @click="goPay">充值</el-button>
              </span>
            </div>
            <div class="price">价格：{{ currentGoods.price || 0 }} 元 = 1 个</div>
          </div>
        </div>
      </div>
      <div class="grid">
        <div class="header">单个下单</div>
        <div class="inner">
          <el-form ref="goodsForm" :model="goodsForm" size="medium" v-if="!disabled">
            <el-form-item
              label=""
              v-for="(item, i) in currentGoods.order_method"
              :key="i"
              :rules="goodsFormRules['value_' + i]"
              :prop="'value_' + i"
            >
              <el-input v-model="goodsForm['value_' + i]" :placeholder="'请输入' + item.name">
                <template slot="prepend" style="width: 100px">{{ item.name }}</template>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="default_num" :rules="goodsFormRules.default_num">
              <el-input v-model="goodsForm.default_num" type="number" :min="1">
                <template slot="prepend">下单数量</template>
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
            <el-form-item label="">
              <el-input :value="(currentGoods.price * goodsForm.default_num).toFixed(2)" :disabled="true">
                <template slot="prepend">需要</template>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit('goodsForm')" style="width: 100%">确认下单</el-button>
            </el-form-item>
          </el-form>
          <div class="fs14" v-if="disabled">禁止下单</div>
        </div>
      </div>
      <div class="grid" style="display: none;">
        <div class="header">批量下单</div>
        <div class="inner">
          <el-input :disabled="true" placeholder="不支持批量下单"></el-input>
        </div>
      </div>
      <div class="grid">
        <div class="header">订单信息</div>
        <div class="inner">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            :cell-style="{ 'text-align': 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column prop="order_no" label="订单号" min-width="180"></el-table-column>
            <el-table-column
              v-for="(item, i) in currentGoods.order_method"
              :key="'b' + i"
              :prop="'value_' + i"
              :label="item.name"
              min-width="120"
            ></el-table-column>
            <el-table-column prop="num" label="下单数量(个)" width="110"></el-table-column>
            <el-table-column prop="pay_amount" label="总价(元)" width="80"></el-table-column>
            <el-table-column prop="order_status" label="状态" width="80"></el-table-column>
            <el-table-column prop="notes" label="备注" width="80"></el-table-column>
            <el-table-column prop="createtime" label="创建时间" min-width="100"></el-table-column>
            <el-table-column prop="operation" label="操作"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import lf from "localforage";
export default {
  props: ["id"],
  data() {
    let validateNum = (rule, value, callback) => {
      let reg = /^[1-9]\d*$/;
      if (!reg.test(value)) {
        callback(new Error("请填写正确的下单数量"));
      } else {
        callback();
      }
    };
    return {
      disabled: false, // 是否禁止下单
      goods: {}, // 所有商品
      name: "",
      currentGoods: {}, // 当前商品信息
      account: {
        level: "",
        balance: 0,
      },
      goodsForm: {
        id: "", // 当前商品id
        name: "",
        order_method: [], // 下单方式
        value_0: "",
        value_1: "",
        value_2: "",
        value_3: "",
        default_num: 0,
        totalPrice: 0,
      },
      goodsFormRules: {
        value_0: [{ required: true, message: "请输入内容", trigger: "blur" }],
        value_1: [{ required: true, message: "请输入内容", trigger: "blur" }],
        value_2: [{ required: true, message: "请输入内容", trigger: "blur" }],
        value_3: [{ required: true, message: "请输入内容", trigger: "blur" }],
        default_num: [
          { required: true, message: "下单数量不能为空", trigger: "blur" },
          { validator: validateNum, trigger: "blur" },
        ],
      },
      // formInline: {
      //   orderCate: "",
      //   orderID: "",
      // },
      tableData: [
        {
          value_0: "",
          value_1: "",
          value_2: "",
          value_3: "",
        },
      ],
    };
  },
  created() {
    this.fetch(this.id);
    this.getAccount();
  },
  mounted() {
    window.scrollTo(0, 0);
  },
  methods: {
    // 获取商品信息
    async fetch(id) {
      const formData = new FormData();
      formData.append("id", id);
      const { data: res } = await this.$http.post("productDetail", formData);
      // console.log(res, "商品详情");
      if (res.code != "0") return this.$message("获取商品详情失败");
      this.currentGoods = res.data;
      this.currentGoods.order_method = JSON.parse(this.currentGoods.order_method);
      // console.log(this.currentGoods, "当前商品");
      this.name = this.currentGoods.name;
      Object.assign(this.goodsForm, this.currentGoods);
      if (!this.id || this.currentGoods.on_shelf == "0") {
        this.disabled = true;
      }
      this.goods = await lf.getItem("goods");
    },
    // 获取账户信息
    async getAccount() {
      const { data: res } = await this.$http.post("memberInfo");
      // console.log(res);
      if (res.code != "0") return this.$message("获取账户信息失败");

      this.account.balance = res.data.balance;
    },
    // 去充值
    goPay() {
      this.$router.push("/center/pay");
    },
    async getOrderDetail(id) {
      const formData = new FormData();
      formData.append("orderId", id);
      const { data: res } = await this.$http.post("orderDetail", formData);
      // console.log(res, "订单详情");
      if (res.code != "0") return this.$message("获取订单信息失败");
      this.loadingEnd();
      this.$confirm("下单成功", "提示", {
        confirmButtonText: "确定",
        type: "success",
        center: true,
        showCancelButton: false,
      })
        .then(() => {
          this.$router.push("/center/myOrder");
        })
        .catch(() => {});

      const statusList = ["待付款", "已付款", "已受理", "处理完成", "取消", "退款"];
      res.data.order_status = statusList[res.data.order_status - 1];
      JSON.parse(res.data.order_method).forEach((item, i) => {
        res.data["value_" + i] = item.value;
      });
      this.tableData = [res.data];
      this.getAccount();
    },
    // 确认下单
    onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return;
        this.loadingStart();
        const arr0 = [];
        for (const key in this.goodsForm) {
          if (this.goodsForm.hasOwnProperty(key)) {
            if (key.includes("value") && this.goodsForm[key]) {
              arr0.push(this.goodsForm[key]);
            }
          }
        }

        arr0.forEach((item0, i) => {
          this.goodsForm.order_method.forEach((item1, j) => {
            if (i === j) {
              item1.value = item0;
            }
          });
        });
        // console.log(JSON.stringify(this.goodsForm.order_method), 222);

        this.goodsForm.totalPrice = (this.currentGoods.price * this.goodsForm.default_num).toFixed(2);
        if (this.goodsForm.totalPrice > this.account.balance) return this.$message.error("余额不足，请充值");
        // console.log(this.goodsForm);
        let order_method = JSON.stringify(this.goodsForm.order_method);
        const formData = new FormData();
        formData.append("productId", this.goodsForm.id);
        formData.append("num", this.goodsForm.default_num);
        formData.append("order_method", order_method);
        const { data: res } = await this.$http.post("orderCreate", formData);
        // console.log(res, "下单返回");
        if (res.code != "0") {
          this.loadingEnd();
          this.$message("下单失败");
        }
        this.getOrderDetail(res.data);
      });
    },
    loadingStart() {
      return this.$loading({
        lock: true,
        text: "下单中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.3)",
      });
    },
    loadingEnd() {
      this.loadingStart().close();
    },
    async handleChange(value) {
      if (this.$route.params.id == value) return;

      await lf.setItem("firstOrderID", value);
      this.$router.replace(`/center/order/${value}`);
    },
  },
};
</script>

<style lang="scss">
.order-wrapper {
  .el-input-group__append,
  .el-input-group__prepend {
    font-size: 12px;
    padding: 0 5px;
    color: #555;
  }
  padding-bottom: 200px;
  .desc {
    min-height: 120px;
    padding: 10px 20px 80px;
    background-color: #e4e6ff;
    border-left: 5px solid #4250f1;
    p {
      margin-bottom: 10px;
    }
  }
  .desc::after {
    content: "";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }
  .grid {
    // width: 48%;
    border-radius: 5px;
    background-color: #fff;
    overflow: hidden;
    .header {
      padding: 15px;
      color: #fff;
    }
    .inner {
      padding: 20px;
      .info {
        border: 1px solid #ddd;
        border-radius: 5px;
        div:nth-child(3) {
          border-bottom: 0;
        }
        > div {
          height: 40px;
          line-height: 40px;
          padding: 0 15px;
          border-bottom: 1px solid #cacaca;
        }
      }
    }
  }
  .grid:nth-child(1) {
    width: 300px;
    margin-right: 30px;
    .header {
      padding: 3px;
      background-image: linear-gradient(to right, #79bd8f, #beeb9f);
      .el-select {
        width: 100%;
        .el-input__inner::placeholder {
          color: #fff;
        }
        .el-input__inner {
          color: #fff;
          background-color: rgba(0, 0, 0, 0);
          border: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .el-input__icon {
          color: #fff;
        }
      }
    }
  }
  .grid:nth-child(2) {
    flex: 1;
    .header {
      background-image: linear-gradient(to right, #7b84ed, #c6c9f1);
    }
  }
  .grid:nth-child(3) {
    .header {
      background-image: linear-gradient(to right, #ae7000, #fed18d);
    }
  }
  .grid:nth-child(4) {
    width: 100%;
    margin-top: 30px;
    .header {
      background-image: linear-gradient(to right, #ae7000, #fed18d);
    }
  }
}
@media screen and (max-width: 1250px) {
  .order-wrapper {
    .grid {
      width: 48%;
    }
  }
}
@media screen and (max-width: 750px) {
  .order-wrapper {
    .grid {
      width: 100%;
    }
  }
}
</style>
